package deep8jvmdvm;

/*
ReentrantLock 基本使用

公平锁使用实例如下：
 */

import utils.PrintlnUtils;

import java.util.concurrent.locks.ReentrantLock;

public class TestReentrantLock2 implements Runnable {
   private int sharedNumber = 0;
    //创建公平锁
    ReentrantLock lock = new ReentrantLock(true);

    @Override
    public void run() {
        while (sharedNumber < 20) {
            lock.lock();
            try {
                sharedNumber++;
                PrintlnUtils.println(Thread.currentThread().getName()+" 获得锁 ，sharedNumber is "+sharedNumber);

            }finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        TestReentrantLock2 testReentrantLock2 = new TestReentrantLock2();
        Thread thread1 = new Thread(testReentrantLock2);
        Thread thread2 = new Thread(testReentrantLock2);
        Thread thread3 = new Thread(testReentrantLock2);
        thread1.start();
        thread2.start();
        thread3.start();
    }
    /*
    运行效果如下：

     Thread-0 获得锁 ，sharedNumber is 1

    Thread-2 获得锁 ，sharedNumber is 2

    Thread-1 获得锁 ，sharedNumber is 3

    Thread-0 获得锁 ，sharedNumber is 4

    Thread-2 获得锁 ，sharedNumber is 5

    Thread-1 获得锁 ，sharedNumber is 6

    Thread-0 获得锁 ，sharedNumber is 7

    Thread-2 获得锁 ，sharedNumber is 8

    Thread-1 获得锁 ，sharedNumber is 9

    Thread-0 获得锁 ，sharedNumber is 10

    Thread-2 获得锁 ，sharedNumber is 11

    Thread-1 获得锁 ，sharedNumber is 12

    Thread-0 获得锁 ，sharedNumber is 13

    Thread-2 获得锁 ，sharedNumber is 14

    Thread-1 获得锁 ，sharedNumber is 15

    Thread-0 获得锁 ，sharedNumber is 16

    Thread-2 获得锁 ，sharedNumber is 17

    Thread-1 获得锁 ，sharedNumber is 18

    Thread-0 获得锁 ，sharedNumber is 19

    Thread-2 获得锁 ，sharedNumber is 20

    Thread-1 获得锁 ，sharedNumber is 21

    Thread-0 获得锁 ，sharedNumber is 22


    可以看出，创建的 3 个线程依次按照顺序去修改 sharedNumber 的值。


     */
}
